<template>
  <div class="out">
     <a-menu
      v-model:openKeys="openKeys"
      v-model:selectedKeys="selectedKeys"
      style="width: 256px"
      mode="inline"
      :items="items"
      @click="handleClick"
    ></a-menu>
    <div>
      <a-spin :spinning="spinning">
      <div id="topbar">
        <div class="file_upload_box">
          <input id="uploadBtn" type="file" @change="loadExcel" />
          <a href="#none">上传文件</a>
        </div>
        <!-- <select v-model="selected" @change="selectExcel">
          <option disabled value="">Choose</option>
          <option v-for="option in options" :key="option.text" :value="option.value">
            {{ option.text }}
          </option>
        </select> -->
        <div>
          <a-button size="larger" @click="downloadExcel" style="margin-left: 300px; margin-top: 10px;">下载到本地</a-button>
        </div>
        <div>
          <a-button @click="save" style="margin-left: 800px; margin-top: 10px;">保存</a-button>
        </div>
      </div>
      </a-spin>
      <div id="luckysheet"></div>
      <div v-show="isMaskShow" id="tip">Downloading</div>

      <a-modal v-bind:open="visible" @ok="handleSave" @cancel="handleCancel" :confirm-loading="confirmLoading">
        <a-form
              :model="formState"
              :rules="rules"
              name="basic"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 14 }"
              autocomplete="off"
              @finish="handleSave"
          >
              <a-form-item
                  label="角色名"
                  name="characterName"
              >
                  <a-input v-model:value="formState.characterName" placeholder="角色名"/>
              </a-form-item>
              <a-form-item
                  label="角色唯一标识名"
                  name="name"
              >
                  <a-input v-model:value="formState.name" placeholder="角色唯一标识名，不可与其他角色的唯一标识名重复"/>
              </a-form-item>
              <a-form-item
                  label="骰娘记录属性"
                  name="rememberedVars"
              >
                  <a-textarea v-model:value="formState.rememberedVars" placeholder="骰娘记录属性"/>
              </a-form-item>
              <a-form-item :wrapper-col="{ span: 14, offset: 10 }">
                  <a-button type="primary" html-type="submit">保存</a-button>
              </a-form-item>
          </a-form>
          <template #footer>
          </template>
      </a-modal>
    </div>
  </div>
</template>
  
<script lang="js">
  export default {
    name: 'Character',
  }
</script>

<script lang="js" setup>
import { reactive, ref, watch, VueElement, h, onMounted } from 'vue';
import { MenuProps, ItemType, Modal } from 'ant-design-vue';
import { exportExcel, saveExcel } from './export'
import LuckyExcel from 'luckyexcel'
import { getCharacterList, getCharacterDetail, saveCharacter } from '../../api/character_api'
import router from '@/router/index';

const selectedKeys = ref(['create']); // 左侧menu选中的key
const openKeys = ref(['sub1']); // 左侧menu打开的key
const username = ref("") // 用户名
const spinning = ref(false)

// 初始化
onMounted(async () => {
  const storedValue = localStorage.getItem('username');
  if (storedValue) {
    username.value = storedValue + '的角色'
  }
  await getCharacterList()
  .then(resp => {
    console.log(resp.data)
    let len = resp.data.length
    for (let i = 0; i < len; i++) {
      let character = resp.data[i]
      items[0].children.push(getItem(character.name, character.id))
    }
  })
  luckysheet.create({
      container: 'luckysheet'
  })
})

function getItem(label, key, icon, children, type) {
  return {
    key,
    icon,
    children,
    label,
    type,
  };
}

const items = reactive([
  getItem( username , 'root', null, []),
  getItem('新建角色', 'create'),
  getItem('返回首页', 'back')
]); // menu中的对象

const handleClick = async e => {
  console.log(e)
  console.log(selectedKeys)
  spinning.value = true
  if (e.key === 'back' ) {
    router.push({ name:'main' })
  } else if (e.key === 'create') {
    luckysheet.destroy()
    luckysheet.create({
      container: 'luckysheet'
    })
    spinning.value = false
    formState.id = 0
    formState.characterName = ''
    formState.name = ''
    formState.rememberedVars = ''
  } else {
    await getCharacterDetail(e.key)
    .then(resp => {
      formState.id = resp.data.id
      formState.characterName = resp.data.characterName
      formState.rememberedVars = resp.data.rememberedVars
      formState.name = resp.data.name
      console.log(resp.data.excelUrl)
      loadExcelFromUrl(resp.data.excelUrl)
    })
  }
}; // menu点击别的菜单的事件

watch(openKeys, val => {
  console.log('openKeys', val);
});

const isMaskShow = ref(false)
const selected = ref('')
const jsonData = ref({})
const options = ref([
  { text: 'Money Manager.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/money-manager-2.xlsx' },
  {
    text: 'Activity costs tracker.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Activity%20costs%20tracker.xlsx'
  },
  {
    text: 'House cleaning checklist.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/House%20cleaning%20checklist.xlsx'
  },
  {
    text: 'Student assignment planner.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20assignment%20planner.xlsx'
  },
  {
    text: 'Credit card tracker.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Credit%20card%20tracker.xlsx'
  },
  { text: 'Blue timesheet.xlsx', value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20timesheet.xlsx' },
  {
    text: 'Student calendar (Mon).xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Student%20calendar%20%28Mon%29.xlsx'
  },
  {
    text: 'Blue mileage and expense report.xlsx',
    value: 'https://minio.cnbabylon.com/public/luckysheet/Blue%20mileage%20and%20expense%20report.xlsx'
  }
])
const name = ref("")
const visible = ref(false) // 保存角色的model是否可见
const formState = reactive({// 表格对象
  id: 0,  
  characterName: '',
  name: '',
  rememberedVars: '',
}); // 保存角色的表单
const rules = { // 表格校验规则
  characterName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  name: [{required: true, message:'请输入唯一角色名', trigger: 'blur'}],
}; // 保存角色的表单的规则

const loadExcelFromUrl = (url) => {
  let file = null
  getFileFromUrl(url,"tmp.xlsx")
  .then((response)=>{
      file = response
      LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
          alert('Failed to read the content of the excel file, currently does not support xls files!')
          return
        }
        console.log('exportJson', exportJson)
        jsonData.value = exportJson
    
        window.luckysheet.destroy()
    
        window.luckysheet.create({
          container: 'luckysheet', //luckysheet is the container id
          showinfobar: false,
          data: exportJson.sheets,
          title: exportJson.info.name,
          userInfo: exportJson.info.name.creator
        })
      })
      spinning.value = false
  })
  .catch((e)=>{
    console.error(e)
  });
} // 从oss的url中获取excel并导入

const loadExcel = (evt) => {
  const files = evt.target.files
  console.log(files[0])
  if (files == null || files.length == 0) {
    alert('No files wait for import')
    return
  }

  let name = files[0].name
  let suffixArr = name.split('.'),
  suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files')
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson)
    jsonData.value = exportJson

    window.luckysheet.destroy()

    window.luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}

const selectExcel = (evt) => {
  const value = selected.value
  const name = evt.target.options[evt.target.selectedIndex].innerText

  if (value == '') {
    return
  }
  isMaskShow.value = true

  LuckyExcel.transformExcelToLuckyByUrl(value, name, (exportJson, luckysheetfile) => {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson)
    jsonData.value = exportJson

    isMaskShow.value = false
    window.luckysheet.destroy()

    window.luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}
const downloadExcel = () => {
  // const value = selected.value;;
  //
  // if(value.length==0){
  //     alert("Please select a demo file");
  //     return;
  // }
  //
  // var elemIF = document.getElementById("Lucky-download-frame");
  // if(elemIF==null){
  //     elemIF = document.createElement("iframe");
  //     elemIF.style.display = "none";
  //     elemIF.id = "Lucky-download-frame";
  //     document.body.appendChild(elemIF);
  // }
  // elemIF.src = value;
  exportExcel(luckysheet.getAllSheets(), '下载')
}

const save = () => {
  visible.value = true
}

const handleSave = (value) => {
  saveCharacter(formState)
  .then(resp => {
    saveExcel(luckysheet.getAllSheets(), resp.data.id)
    visible.value = false
    if (formState.id == 0) {
      items[0].children.push(getItem(resp.data.name, resp.data.id))
    }
  })
  .catch(error => {
    message.error('接口错误！')
  })
}

const handleCancel= () => {
  visible.value = false
}

const getFileFromUrl= (url, fileName) => {
  return new Promise((resolve, reject) => {
      var blob = null;
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.setRequestHeader('Accept', 'image/png');
      xhr.responseType = "blob";
      // 加载时处理
      xhr.onload = () => {
        // 获取返回结果
          blob = xhr.response;
          let file= new File([blob], fileName, { type: 'image/png' });
          // 返回结果
          resolve(file);
      };
      xhr.onerror = (e) => {
          reject(e)
      };
      // 发送
      xhr.send();
  });
}
</script>

<style lang="scss" scoped>
.out {
  margin-top: 0px;
  display: flex;
}
#luckysheet {
    margin: 0px;
    padding: 0px;
    width:  1660px;
    left: 0px;
    top: 30px;
    bottom: 0px;
    position: absolute;
    margin-left: 258px;
    margin-top: 100px;
  }
  
  #uploadBtn {
    font-size: 16px;
  }
  
  #tip {
    position: absolute;
    z-index: 1000000;
    left: 0px;
    top: 0px;
    bottom: 0px;
    right: 0px;
    background: rgba(255, 255, 255, 0.8);
    text-align: center;
    font-size: 40px;
    align-items: center;
    justify-content: center;
    display: flex;
  }

  #topbar{
    display: grid; 
    grid-template-columns: 15% 15% 70%;
    grid-template-rows: 100%;

  }

.file_upload_box {
    display: inline-block;
    width: 200px;
    height: 60px;
    position: relative;
    overflow: hidden;
}
.file_upload_box input[type=file] {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    line-height: 60px;
    opacity: 0;
    cursor: pointer;
}
.file_upload_box a {
    display: inline-block;
    width: 100%;
    line-height: 45px;
    text-align: center;
    font-family: "Microsoft yahei";
    color: black;
    font-weight: 700;
    text-decoration: none;
}
</style>